<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/8/8
 * Time: 14:01
 */

namespace console\controllers\platform;

use business\company\services\SupplierService;
use business\elasticsearch\models\SupplierModel;
use common\cache\CacheManager;
use common\utils\DateTimeUtils;
use console\controllers\BaseIndexController;

class SupplierIndexController extends BaseIndexController
{
    public function actionFull()
    {
        $supplier_service = new SupplierService();
        $supplier_ids = $supplier_service->getSupplierIdsList();
        if (empty($supplier_ids)) {
            echo '没有找到供应商';
            return;
        }
        $this->handSupplierData($supplier_ids);
    }

    public function actionIncrement()
    {
        //1.获取上次查询的时间点
        $timestamp = CacheManager::get(BaseIndexController::LATEST_PLATFORM_SUPPLIER_QUERY_TIME_KEY);
        $now = DateTimeUtils::time();
        if (empty($timestamp)) {
            $timestamp = strtotime('-' . BaseIndexController::DEFAULT_INCREMENT_TIME . ' minutes', $now);
        }
        $last_query_time = date('Y-m-d H:i:s', $timestamp);
        \Yii::info("elasticsearch increment time of platform supplier index update is " . $last_query_time);
        $supplier_service = new SupplierService();
        $supplier_ids = $supplier_service->getSupplierIdsList($last_query_time);
        CacheManager::set(BaseIndexController::LATEST_PLATFORM_SUPPLIER_QUERY_TIME_KEY, $now, 0);
        if (empty($supplier_ids)) {
            echo '没有找到供应商';
            return;
        }
        $this->handSupplierData($supplier_ids);
    }

    private function handSupplierData(&$supplier_ids)
    {
        $supplier_count = count($supplier_ids);
        $loop_count = intval($supplier_count / $this->_every_time_number) + 1;
        echo '总数: ' . $supplier_count . PHP_EOL;
        echo 'all supplier_ids is ' . implode(',', $supplier_ids) . PHP_EOL;
        echo '正在进行: ';
        for ($i = 0; $i < $loop_count; $i++) {
            echo $i . ' ';
            for ($j = $i * $this->_every_time_number; $j < ($i + 1) * $this->_every_time_number && $j < $supplier_count; $j++) {
                $supplier_id = $supplier_ids[$j];
//                $supplier_id = 'G017927';
                $supplier_info = [];
                try {
                    $supplier_info = $this->getDetailSupplierInfo($supplier_id);
                    $supplier_es_model = SupplierModel::findOne($supplier_id);
                    //校验条件
                    $checkResult = $this->checkConstructIndexCondition($supplier_id, $supplier_info);
                    if (!$checkResult['success']) {
                        if ($supplier_es_model) {
                            $supplier_es_model->deleteAll(['_id'=>$supplier_id]);
                        }
                        continue;
                    }
                    if (empty($supplier_es_model)) {
                        $supplier_es_model = new SupplierModel();
                        $supplier_es_model->primaryKey = $supplier_id;
                    }
                    $supplier_es_model->setAttributes($supplier_info, false);
                    $supplier_es_model->indexCreatedTime = date('Y-m-d H:i:s');
                    $rs = $supplier_es_model->save();
                    if (!$rs) {
                        \Yii::error('update es_supplier failed! supplier_id:' . $supplier_id);
                    }
                    echo 'success supplier_id is ' . $supplier_id . PHP_EOL;
                } catch (\Exception $e) {
                    echo 'update failed! supplier_id:' . $supplier_id . PHP_EOL;
//                    var_dump($supplier_info['inStorageCount']);
                    $title = isset($supplier_info['companyName']) ? $supplier_info['companyName'] : '';
                    $this->saveUnIndexData('es_supplier', $title, $supplier_id, $e);
                }
            }
        }
        //理论上不存在物理删除的数据，所以不做该处理

        echo '处理结束' . PHP_EOL;
    }

    /**
     * 获取供应商详细信息
     * @param $supplier_id
     * @return array
     */
    private function getDetailSupplierInfo($supplier_id)
    {
        $supplierService = new SupplierService();

        //获取基本信息
        $basicInfo = $supplierService->getSupplierBasicInfo($supplier_id);

        //获取服务分类
        $categoryInfo = $supplierService->getSupplierCategoryInfo($supplier_id);

        //获取服务资质信息
        $qualifiesInfo = $supplierService->getSupplierQualifies($supplier_id);

        //获取用户信息
        $userInfo = $supplierService->getSupplierUser($supplier_id);

        //获取项目案例信息
        $projectInfo = $supplierService->getSupplierProjects($supplier_id);

        //获取中标信息
        $biddingInfo = $supplierService->getSupplierAwardBidding($supplier_id);

        //获取产品信息
        $productInfo = $supplierService->getSupplierProducts($supplier_id);

        //获取排序信息
        $sortInfo = $supplierService->getSupplierSortInfo($supplier_id, $basicInfo);

        //获取其他信息
        $otherInfo = $supplierService->getSupplierOtherInfo($supplier_id);

        //获取被推荐数
        $recommendCount = (int)$supplierService->getSupplierRecommend($supplier_id);

        //获取被入库数
        $inStorageCount = (int)$supplierService->getSupplierInStorage($supplier_id);

        //获取行业数据
        $industryData = $supplierService->getIndustryData(
            $basicInfo['regLocationCode'],
            $basicInfo['regLocationCity'],
            $basicInfo['companyName']
        );

        return array_merge($basicInfo, $categoryInfo, $qualifiesInfo, $userInfo, $projectInfo, $biddingInfo,
            $productInfo, $sortInfo, $otherInfo, $industryData, ['recommendCount' => $recommendCount, 'inStorageCount' => $inStorageCount]);
    }

    /**
     * 检查索引构建的条件
     * @param $supplierId
     * @param $supplierInfo
     * @return array
     */
    private function checkConstructIndexCondition($supplierId, $supplierInfo)
    {
        $result = [
            'success' => true,
            'errMsg' => ''
        ];

        //供应商id为空
        if ($result['success'] && empty($supplierId)) {
            $result['errMsg'] = '供应商id为空，此条数据不会导入搜索引擎！';
            $result['success'] = false;
        }
        //供应商为测试数据(以test开头则为测试数据)
        if ($result['success'] && (!isset($supplierInfo['companyName']) || !strncmp($supplierInfo['companyName'],
                    'test', 4))
        ) {
            $result['errMsg'] = "此供应商($supplierId)为测试数据，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //供应商基础分类为空
        if ($result['success'] && (!isset($supplierInfo['basicCategoryCode']) || empty($supplierInfo['basicCategoryCode']))) {
            $result['errMsg'] = "此供应商($supplierId)没有基础分类，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //供应商未通过审核或已冻结不进入搜索引擎
        if ($result['success'] && ($supplierInfo['state']!=2 || $supplierInfo['status']!=2)) {
            $result['errMsg'] = "此供应商($supplierId)没有未通过审核或已冻结，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //非合规性数据持久化
        if (!$result['success']) {
            $title = isset($supplierInfo['companyName']) ? $supplierInfo['companyName'] : '';
            $this->saveUnIndexData('es_supplier', $title, $supplierId, $result['errMsg']);
        }

        return $result;
    }

}
